<template>
  <div class='users_container'>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 搜索与添加区域 -->
      <el-row :gutter="20">
        <el-col :span="7">
          <el-input placeholder="请输入内容" v-model.trim="queryInfo.query" clearable @clear="searchUser">
            <el-button slot="append" icon="el-icon-search" @click="searchUser"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="add">添加用户</el-button>
        </el-col>
      </el-row>

      <el-table :data="userList" stripe border>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column label="角色">
          <template scope="{ row }">
            <el-tag type="primary">{{ row.role_name }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="mobile" label="状态">
          <template scope="{ row }">
            <el-switch v-model="row.mg_state" active-color="#13ce66" inactive-color="#ff4949"
              @change="updateState(row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template scope="{ row }">
            <el-button type="primary" size="mini" icon="el-icon-edit" @click="editUser(row.id)"></el-button>
            <el-button type="danger" size="mini" icon="el-icon-delete" @click="delUser(row.id)"></el-button>
            <el-tooltip class="item" effect="dark" content="分配角色" placement="top" :enterable="false">
              <el-button type="warning" size="mini" icon="el-icon-setting" @click="setRole(row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum" :page-sizes="[1, 3, 5, 10]" :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </el-card>

    <!-- 添加用户对话框 -->
    <el-dialog title="添加用户" :visible.sync="addDialogVisible" width="50%">
      <!-- 对话框主体区域 -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password" type="password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 对话框底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="编辑用户" :visible.sync="editDialogVisible" width="50%">
      <!-- 对话框主体区域 -->
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="70px">
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 对话框底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="editUserIfo">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="分配角色" :visible.sync="setRoledialogVisible" width="50%" @close="setRoleDialogClosed">
      <p>当前用户: {{ userInfo.username }}</p>
      <p>当前角色: {{ userInfo.role_name }}</p>
      <el-select v-model="selectRoleId" placeholder="请选择角色">
        <el-option v-for="item in roleList" :key="item.id" :label="item.roleName" :value="item.id"></el-option>
      </el-select>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRoledialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import user from '@/api/user'
import rights from '@/api/rights'

export default {
  name: 'MyUsers',
  data () {
    // 验证手机号码的规则
    const checkMobile = (rule, value, callback) => {
      const regMobile = /^1[34578]\d{9}$/
      if (regMobile.test(value)) {
        return callback()
      }
      // 返回一个错误提示
      callback(new Error('请输入合法的手机号码'))
    }
    return {
      userList: [],
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 3
      },
      total: 10,
      addDialogVisible: false,
      editDialogVisible: false,
      editId: 0,
      setRoledialogVisible: false,
      userInfo: {},
      roleList: [],
      selectRoleId: '',
      // 添加用户表单
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 修改用户表单
      editForm: {
        username: '',
        email: '',
        mobile: ''
      },
      // 表单验证规则
      addFormRules: {
        username: [
          { required: true, message: '请输入用户名称', trigger: 'blur' },
          { min: 3, max: 10, message: '用户名在3~10个字符之间', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '密码在6~15个字符之间', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { type: 'email', message: '邮箱格式不正确，请重新输入', trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { validator: checkMobile, message: '手机号码不正确，请重新输入', trigger: 'blur' }
        ]
      },
      editFormRules: {
        username: [
          { required: true, message: '请输入用户名称', trigger: 'blur' },
          { min: 3, max: 10, message: '用户名在3~10个字符之间', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { type: 'email', message: '邮箱格式不正确，请重新输入', trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { validator: checkMobile, message: '手机号码不正确，请重新输入', trigger: 'blur' }
        ]
      }
    }
  },
  components: {
  },
  methods: {
    // 1.获取用户列表
    async getUserList () {
      const { data: res } = await user.getUserList(this.queryInfo)
      if (res.meta.status === 200) {
        this.userList = res.data.users
        this.total = res.data.total
      } else {
        this.$message.error(res.meta.msg)
      }
    },

    // 2.编辑用户
    async editUser (id) {
      this.editId = id
      this.editDialogVisible = true
      const { data: res } = await user.getUserInfoById(id)
      if (res.meta.status === 200) {
        this.editForm.username = res.data.username
        this.editForm.email = res.data.email
        this.editForm.mobile = res.data.mobile
      } else {
        this.$message.error(res.meta.msg)
      }
    },

    // 3.删除用户
    async delUser (id) {
      this.$confirm('确定永久删除该用户?', '提示', { type: 'warning' }).then(async () => {
        const { data: res } = await user.delUser(id)
        if (res.meta.status === 200) {
          this.getUserList()
          this.$message.success(res.meta.msg)
        } else {
          this.$message.error(res.meta.msg)
        }
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },

    // 4.输入条件查询用户
    searchUser () {
      this.getUserList()
    },

    // 5.切换每页大小
    handleSizeChange (val) {
      this.queryInfo.pagesize = val
      this.getUserList()
    },

    // 6.切换当前页
    handleCurrentChange (val) {
      this.queryInfo.pagenum = val
      this.getUserList()
    },

    // 7.更改用户状态
    async updateState (userInfo) {
      const { data: res } = await user.updateUserState(userInfo.id, userInfo.mg_state)
      if (res.meta.status === 200) {
        this.$message.success(res.meta.msg)
      } else {
        // 更新失败则回弹
        userInfo.mg_state = !userInfo.mg_state
        this.$message.error(res.meta.msg)
      }
    },

    // 8.添加用户
    add () {
      this.addDialogVisible = true
      // 清空表单数据
      this.addForm = {}
    },

    // 9.确认添加用户
    addUser () {
      // 兜底校验
      this.$refs.addFormRef.validate(async valid => {
        if (valid) {
          const { data: res } = await user.addUser(this.addForm)
          if (res.meta.status === 201) {
            this.$message.success(res.meta.msg)
            this.cancel()
            this.getUserList()
          } else {
            this.$message.error(res.meta.msg)
          }
        } else {
          return false
        }
      })
    },

    // 10.取消操作
    cancel () {
      this.addDialogVisible = false
      this.editDialogVisible = false
    },

    // 11.确认修改用户信息
    editUserIfo () {
      // 兜底校验
      this.$refs.editFormRef.validate(async valid => {
        if (valid) {
          const { data: res } = await user.updateUserInfo(this.editId, this.editForm)
          if (res.meta.status === 200) {
            this.$message.success(res.meta.msg)
            this.cancel()
            this.getUserList()
          } else {
            this.$message.error(res.meta.msg)
          }
        } else {
          return false
        }
      })
    },

    // 12.分配角色
    async setRole (row) {
      this.userInfo = row
      this.setRoledialogVisible = true
    },

    // 13.获取角色列表
    async getRoleList () {
      const { data: res } = await rights.getRolesList()
      res.data.forEach(item => {
        this.roleList.push(item)
      })
    },

    // 14.确认添加角色
    async saveRoleInfo () {
      if (!this.selectRoleId) {
        return this.$message.error('请选择要分配角色!')
      }
      const { data: res } = await rights.setUserRole(this.userInfo.id, this.selectRoleId)
      if (res.meta.status === 200) {
        this.getUserList()
        this.setRoledialogVisible = false
        this.$message.success(res.meta.msg)
      } else {
        this.$message.error(res.meta.msg)
      }
    },

    // 15.监听分配角色对话框
    setRoleDialogClosed () {
      this.selectRoleId = ''
      this.userInfo = {}
    }

  },
  created () {
    this.getUserList()
    this.getRoleList()
  },
  mounted () {
  }
}
</script>

<style lang='less' scoped>
.el-breadcrumb {
  line-height: 50px;
}

.el-table {
  margin-top: 15px;
}

.el-pagination {
  margin-top: 15px;
}
</style>
